<template>
  <view class="detail-container" v-if="isLoading">
    <!-- 标题与封面图 -->
    <view class="header-section" v-if="detailData.images.length>0">
		<swiper  :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000">
			<swiper-item v-for="(item, index) in detailData.images" :key="index">
				 <img :src="getBaseUrl+'/'+item" mode="aspectFit" style="width: 100vw;height: 100%;"/>
			</swiper-item>
		</swiper>
      <!-- <image class="cover" :src="detailData.cover" mode="aspectFill" /> -->
      <view class="title-box">
        <text class="main-title">{{ detailData.title }}</text>
        <view class="meta-info">
			<!-- class="category-tag" -->
          <text  :class="{
    'category-tag': detailData.category === '消息',
    'category-tag2': detailData.category === '活动',
    'category-tag3': detailData.category === '通知'
  }">{{ detailData.category }}</text>
         <text class="publish-time">{{ detailData.publishTime }}</text>
        </view>
      </view>
    </view>
<view class="share-btn" @click="handleShare">
		        <image src="/static/share.png" class="share-icon" />
		      </view>
    <!-- 核心内容区域 -->
    <view class="content-section">
      <view class="author-info">
        <image class="author-avatar" :src="'/static/logo.png'" />
        <text class="author-name">厦工华为坊</text>
		<!-- here -->
		
			  	<!-- here -->
      </view>
     <rich-text 
       :nodes="formatRichText(detailData.content)"
       class="rich-text-container"
       :style="{fontSize: '28rpx', lineHeight: '1.6'}"
     ></rich-text>
      <!-- <rich-text :nodes="detailData.content" class="article-content" /> -->
<text class="stat-item">浏览 {{viewCount}}</text>
      <!-- 活动专属信息 -->
	 <view v-if="detailData.type === 'event' && isEnding==false" class="action-section">
	   <view class="stats-line">
	     
	     <text class="stat-item">报名 {{applyCount}}</text>
		 <button class="register-btn" @click="jumpToRegistration">
		   {{ isRegistered ? '查看状态' : '立即报名' }}
		 </button>
	   </view>
	 </view>
    
    </view>
  </view>
  <view v-else style="margin-left: 43%;margin-top: 80%;">加载中...</view>
</template>
<script setup>
import { ref } from 'vue'
import { onMounted } from 'vue';
import getBaseUrl from '../../../utils/baseUrl.js'
// 新增统计变量（写死数据）
const viewCount = ref(0)
const applyCount = ref(0)
const isLoading = ref(false)
const isEnding = ref(true)
const detailData = ref({
  type: 'event', // 可切换为'event'
  images:[],
  title: '100',
  cover: '/static/event-cover.jpg',
  category: '',
  publishTime: '',
  author: {
    name: '厦工华为坊',

  },
  content:'',
  // 活动专属字段
  eventDate:'',
  location: ''
})

 const formatRichText = (html) => {
  let newContent = html
    // 移除原有尺寸属性
    .replace(/<img[^>]*>/gi, (match) => {
      return match
        .replace(/style=('|").*?('|")/gi, '')
        .replace(/width=('|").*?('|")/gi, '')
        .replace(/height=('|").*?('|")/gi, '');
    })
    // 添加自适应样式
    .replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:10rpx auto;"');
  return newContent;
};
const jumpToRegistration = () => {
  uni.navigateTo({
    url: `/pages/home/event-register/event-register?id=${detailData.value.contentId}&needscore=${detailData.value.requiredIntegral}`
  })
}


// 添加分享处理逻辑
// 分享处理函数修改后版本
const handleShare = async () => {
  const shareInfo = {
    title: detailData.value.title,
    content: detailData.value.content?.substring(0, 50) + '...' || '分享内容',
    url: `${window.location.origin}/pages/home/detail/detail?id=${detailData.value.contentId}`,
    image: detailData.value.images[0] 
      ? `${getBaseUrl.value}/${detailData.value.images[0]}`
      : `${getBaseUrl.value}/static/logo.png`
  }

  // #ifdef H5
  try {
    // 现代浏览器分享方案
    if (navigator.share) {
      await navigator.share({
        title: shareInfo.title,
        text: shareInfo.content,
        url: shareInfo.url
      })
      uni.showToast({ title: '分享成功' })
    } 
    // 传统浏览器处理方案
    else {
      await copyToClipboard(shareInfo.url)
      uni.showModal({
        title: '分享提示',
        content: '链接已复制到剪贴板，请手动分享',
        showCancel: false
      })
    }
  } catch (error) {
    if (error.name !== 'AbortError') {
      console.error('分享失败:', error)
    }
  }
  // #endif

  // #ifdef APP-PLUS
  uni.share({
    provider: 'weixin',
    scene: 'WXSceneSession',
    type: 0,
    title: shareInfo.title,
    summary: shareInfo.content,
    href: shareInfo.url,
    imageUrl: shareInfo.image,
    success: () => uni.showToast({ title: '分享成功' }),
    fail: (err) => console.error('分享失败:', err)
  })
  // #endif
}

// 剪贴板复制工具函数
const copyToClipboard = (text) => {
  return new Promise((resolve, reject) => {
    const input = document.createElement('textarea')
    input.value = text
    document.body.appendChild(input)
    input.select()
    try {
      document.execCommand('copy')
      resolve()
    } catch (err) {
      reject(err)
    } finally {
      document.body.removeChild(input)
    }
  })
}

// 微信小程序原生分享
// // #ifdef MP-WEIXIN
// onShareAppMessage(() => ({
//   title: detailData.value.title,
//   path: `/pages/home/detail/detail?id=${detailData.value.contentId}`,
//   imageUrl: detailData.value.images[0] 
//     ? `${getBaseUrl}/${detailData.value.images[0]}`
//     : ''
// }))
// // #endif


const isRegistered = ref(false)
import { onLoad } from '@dcloudio/uni-app';
import { http } from '../../../utils/requestUtil';
onLoad(async (options) => {
  try {
    // 并行执行两个独立请求
    const [registrationRes, contentRes] = await Promise.all([
      http.get(`/bole/registration/registionInfo/${options.id}`),
      http.get(`/bole/content/${options.id}`)
    ]);

    // 处理注册信息
    if (registrationRes.data) {
      isRegistered.value = true;
    }

    // 处理内容详情
    const categoryMap = { 1: 'news', 2: 'event', 3: 'notice' };
    const categoryMap2 = { 1: '消息', 2: '活动', 3: '通知' };
    
    // 处理图片列表
    let imgUrlArray = [];
    if (contentRes.data.boleContentImageList.length !== 0) {
      imgUrlArray = contentRes.data.boleContentImageList[0].imgUrl.split(',');
      // 注意：这里的路径替换可能需要根据实际环境调整（D:/ruoyi/uploadPath 可能仅用于本地测试）
    }

    // 统一更新详情数据
    detailData.value = {
      ...detailData.value,
      images: imgUrlArray,
      title: contentRes.data.title,
      contentId: contentRes.data.contentId,
      categoryId: contentRes.data.categoryId,
      content: contentRes.data.content,
      type: categoryMap[contentRes.data.contentType] || 'news',
      category: categoryMap2[contentRes.data.contentType] || '新闻',
      publishTime: contentRes.data.createTime,
      eventDate: contentRes.data.eventTime,
	  requiredIntegral:contentRes.data.requiredIntegral,
	  regEndTime:contentRes.data.regEndTime
    };
	const date1 = new Date(contentRes.data.regEndTime);
	const date2 = new Date();
    isEnding.value = date1 < date2
    // 获取流量信息（可放在并行请求之后，因为可能依赖内容详情的结构）
    const viewAndApply = await http.get(`/bole/content/registration/${options.id}`);
    viewCount.value = viewAndApply.data.viewCount + 1;
    applyCount.value = viewAndApply.data.registrationCount;
	//显示
    isLoading.value=true
    // 浏览量加1（无需等待响应，可发送后直接继续）
    http.get(`/bole/content/view/${options.id}`);

  } catch (error) {
    console.error('请求失败:', error);
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'error',
      duration: 2000
    });
    // uni.navigateBack(); // 可根据需求决定是否返回
  }
});

</script>
<script>
// 单独添加这个script块处理微信分享
// #ifdef MP-WEIXIN
export default {
  onShareAppMessage() {
    return {
      title: this.detailData.title,
      path: `/pages/home/detail/detail?id=${this.detailData.contentId}`,
      imageUrl: this.detailData.images[0] 
        ? `${this.getBaseUrl}/${this.detailData.images[0]}`
        : ''
    }
  }
}
// #endif
</script>
<style>
	.content-section >>> .rich-text-container {
	  white-space: pre-wrap !important;
	  word-break: break-all;
	}
	
	/* 调整现有样式 */
	.content-section {
	  padding: 32rpx;
	  line-height: 1.8;
	  color: #303133;
	  /* 增加以下声明 */
	  white-space: pre-wrap;
	}
/* 基础容器增加内阴影提升层次感 */
.detail-container {
	height: 100vh;
  background: white;
  box-shadow: inset 0 8rpx 16rpx rgba(0,0,0,0.02);
}

/* 头部轮播图优化 */
.header-section {
  border-radius: 0 0 24rpx 24rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(47,128,237,0.15);
  height: auto; /* 移除固定高度，改为自适应 */
}

/* 标题区域优化 */
.title-box {
  padding: 24rpx 32rpx;
  background: linear-gradient(transparent, rgba(0,0,0,0.7));
  position: static; /* 改为静态定位，配合轮播图自适应 */
}
.main-title {
  font-size: 44rpx;
  text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.3);
  color: #fff; /* 显式声明文字颜色 */
}

/* 分类标签优化 */
.category-tag {
  background: rgba(64,158,255,0.15);
  color: #409EFF;
  font-weight: 500;
  padding: 12rpx 24rpx; /* 增大内边距 */
  border-radius: 999rpx; /* 改为圆角胶囊形 */
}
.category-tag2 {
  background: rgba(103,194,58,0.15);
  color: #67c23a;
  font-weight: 500;
  padding: 12rpx 24rpx;
  border-radius: 999rpx;
}
.category-tag3 {
  background: rgba(230,162,60,0.15);
  color: #e6a23c;
  font-weight: 500;
  padding: 12rpx 24rpx;
  border-radius: 999rpx;
}
.publish-time {
  color: #606266; /* 更新时间颜色 */
}

/* 作者信息优化 */
.author-info {
  padding: 24rpx;
  background: rgba(255,255,255,0.9);
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.06);
  margin-bottom: 32rpx; /* 增加底部间距 */
}
.author-avatar {
  width: 50rpx; /* 增大头像尺寸 */
  height: 50rpx;
  margin-right: 24rpx; /* 增大右侧间距 */
}

/* 统计信息与按钮优化 */
.action-section {
  position: sticky;
  bottom: 0;
  background: rgba(255,255,255,0.96);
  backdrop-filter: blur(10rpx);
  padding: 24rpx 32rpx;
  box-shadow: 0 -4rpx 16rpx rgba(0,0,0,0.05);
  display: flex;
  justify-content: space-between; /* 左右分布 */
  align-items: center;
}

.stats-line {
  display: flex;
  align-items: center;
  gap: 32rpx;
}

.stat-item {
  font-size: 28rpx;
  color: #606266;
  display: flex;
  align-items: center;
  padding: 12rpx 24rpx;
  background: rgba(144,147,153,0.08);
  border-radius: 999rpx; /* 圆角胶囊形 */
}

.stat-item::before {
  content: ''; /* 改为纯色方块图标 */
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  margin-right: 12rpx;
}

.stat-item:first-child::before {
  background: #409EFF; /* 第一个图标蓝色 */
}

.stat-item:last-child::before {
  background: #67c23a; /* 最后一个图标绿色 */
}

.register-btn {
  flex: none;
  height: 80rpx;
  min-width: 240rpx;
  border-radius: 48rpx;
  font-weight: 500;
  transition: all 0.3s;
  background: linear-gradient(135deg, #409EFF, #3375e0);
  box-shadow: 0 6rpx 16rpx rgba(64,158,255,0.3);
  color: white; /* 显式声明文字颜色 */
  border: none; /* 移除默认边框 */
}

.register-btn:active {
  transform: scale(0.98);
  opacity: 0.9;
}

/* 内容区域优化 */
.content-section {
  padding: 32rpx;
  line-height: 1.8;
  color: #303133;
}

.content-section >>> img {
  border-radius: 12rpx;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.08);
}

/* 新增分享按钮样式 */
.share-btn {
  position: fixed;
  right: 30rpx;
  bottom: 30rpx;
  padding: 16rpx;
  background: rgba(255,255,255,0.9);
  border-radius: 50%;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}

.share-icon {
  width: 40rpx;
  height: 40rpx;
  display: block;
}

/* 微信小程序隐藏分享按钮 */
/* #ifdef MP-WEIXIN */
.share-btn {
  display: none;
}
/* #endif */
</style>